<template>
  <div class="list-container">
    <h2 class="page-title">
      <i class="fas fa-list-ul" style="color: #42b983; margin-right: 10px;"></i>
      简历列表
    </h2>

    <!-- 统计信息卡片1 -->
    <div class="stats-card">
      <div class="stat-item">
        <span class="stat-label">总简历数</span>
        <span class="stat-value">{{ resumes.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">本科及以上学历</span>
        <span class="stat-value">{{
            resumes.filter((r) => ['本科', '硕士', '博士'].includes(r.education)).length
          }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">有工作经验</span>
        <span class="stat-value">{{
            resumes.filter((r) => r.work_experiences && r.work_experiences.length > 0).length
          }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">平均简历评分</span>
        <span class="stat-value">{{
            resumes.length > 0
                ? (resumes.reduce((sum, r) => sum + (r.resume_score || 0), 0) / resumes.length).toFixed(1)
                : '0.0'
          }}</span>
      </div>
    </div>

    <!-- 搜索框和操作按钮 -->
    <div class="search-box">
      <input
          v-model="searchKeyword"
          type="text"
          placeholder="搜索姓名、期望职位、手机号..."
          class="search-input"
          @input="debounceSearch(300)"
      />
      <button
          @click="resetSearch()"
          class="btn btn-secondary btn-sm"
          style="margin-left: 10px;"
      >
        <i class="fas fa-times"></i> 重置
      </button>
      <button
          @click="goToExport()"
          class="btn btn-primary btn-sm"
          style="margin-left: 10px;"
      >
        <i class="fas fa-file-export" style="margin-right: 5px;"></i>
        导出简历
      </button>
    </div>

    <!-- 简历列表卡片 -->
    <div class="resume-list">
      <div
          v-for="resume in filteredResumes"
          :key="resume.id"
          class="resume-card"
          @click="goToDetail(resume.id)"
      >
        <div class="card-header">
          <h3 class="card-name">
            {{ resume.name }}
            <span class="card-badge">{{ resume.education }}</span>
          </h3>
          <span class="card-id">ID：{{ resume.id }}</span>
        </div>
        <div class="card-body">
          <div class="card-item">
            <i class="fas fa-briefcase" style="color: #42b983; margin-right: 5px;"></i>
            <span>期望职位：{{ resume.expectedJob }}</span>
          </div>
          <div class="card-item">
            <i class="fas fa-graduation-cap" style="color: #42b983; margin-right: 5px;"></i>
            <span>应届年份：{{ resume.graduate_year || "无" }}</span>
          </div>
          <div class="card-item">
            <i class="fas fa-phone" style="color: #42b983; margin-right: 5px;"></i>
            <span>手机号：{{ resume.phone }}</span>
          </div>
          <div class="card-item">
            <i class="fas fa-star" style="color: #42b983; margin-right: 5px;"></i>
            <span>简历评分：{{ resume.resume_score || 0 }}分</span>
          </div>
          <div class="card-footer">
            <span class="card-tag">工作经历：{{ (resume.work_experiences || []).length }}条</span>
            <span class="card-tag">项目经历：{{ (resume.project_experiences || []).length }}条</span>
            <span class="card-tag">教育经历：{{ (resume.education_experiences || []).length }}条</span>
          </div>
        </div>
        <div class="card-action">
          <button
              @click.stop="goToDetail(resume.id)"
              class="btn btn-primary"
          >
            <i class="fas fa-eye" style="margin-right: 5px;"></i>
            查看详情
          </button>
        </div>
      </div>

      <!-- 空数据提示 -->
      <div v-if="filteredResumes.length === 0 && !loading && !error" class="empty-container">
        <div class="empty-icon">
          <i class="fas fa-file-alt" style="font-size: 64px; color: #ccc;"></i>
        </div>
        <div class="empty-text">暂无匹配的简历数据</div>
        <div class="empty-desc">
          {{ searchKeyword ? '请尝试其他搜索关键词' : '还没有用户提交简历' }}
        </div>
        <button
            @click="goToCreate()"
            class="btn btn-primary btn-lg"
            style="margin-top: 20px;"
            v-if="!searchKeyword"
        >
          <i class="fas fa-plus" style="margin-right: 5px;"></i>
          提交简历
        </button>
      </div>

      <!-- 加载中提示 -->
      <div v-if="loading" class="loading-container">
        <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #42b983;"></i>
        <div class="loading-text">加载中...</div>
      </div>

      <!-- 加载失败提示 -->
      <div v-if="error" class="error-container">
        <i class="fas fa-exclamation-circle" style="font-size: 36px; color: #ff4d4f;"></i>
        <div class="error-text">{{ error }}</div>
        <button
            @click="fetchResumes()"
            class="btn btn-primary"
            style="margin-top: 20px;"
        >
          <i class="fas fa-sync-alt" style="margin-right: 5px;"></i>
          重试
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();

// 状态变量
const resumes = ref([]); // 原始简历列表数据
const loading = ref(true); // 加载状态
const error = ref(''); // 错误信息
const searchKeyword = ref(''); // 搜索关键词
const filteredResumes = ref([]); // 过滤后的简历列表

// 页面加载时获取简历列表
onMounted(() => {
  fetchResumes();
});

// 监听路由变化，每次进入简历列表页面时都刷新数据
watch(() => route.path, (newPath) => {
  if (newPath === '/resume') {
    // 进入简历列表页面，刷新数据
    fetchResumes();
  }
}, { immediate: false });

// 调用后端接口获取简历列表
const fetchResumes = async () => {
  loading.value = true;
  error.value = '';
  try {
    // 后端路由：path('resume/', include('resume.urls'))，所以完整路径是 http://127.0.0.1:8000/resume/resumes/
    const response = await axios.get('http://127.0.0.1:8000/resume/resumes/', {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    // 后端返回的直接是数组
    const data = response.data;
    resumes.value = Array.isArray(data) ? data : [];
    filteredResumes.value = [...resumes.value]; // 初始显示所有数据
    
    console.log('获取到的简历数据:', resumes.value);
  } catch (err) {
    console.error('获取简历列表失败:', err);
    if (err.response && err.response.status === 404) {
      error.value = '接口不存在，请检查后端路由配置';
    } else if (err.message && (err.message.includes('Network Error') || err.message.includes('ERR_CONNECTION_REFUSED'))) {
      error.value = '无法连接到服务器，请检查后端是否启动（http://127.0.0.1:8000）！';
    } else {
      error.value = '加载简历失败：' + (err.message || '未知错误');
    }
  } finally {
    loading.value = false;
  }
};

// 防抖搜索（避免输入时频繁过滤）
let debounceTimer = null;
const debounceSearch = (delay) => {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    filterResumes();
  }, delay);
};

// 过滤简历（根据搜索关键词）
const filterResumes = () => {
  if (!searchKeyword.value.trim()) {
    filteredResumes.value = [...resumes.value];
    return;
  }
  const keyword = searchKeyword.value.trim().toLowerCase();
  filteredResumes.value = resumes.value.filter(resume => {
    // 搜索字段：姓名、期望职位、手机号、应届年份、个人优势
    return (
        (resume.name && resume.name.toString().toLowerCase().includes(keyword)) ||
        (resume.expectedJob && resume.expectedJob.toString().toLowerCase().includes(keyword)) ||
        (resume.phone && resume.phone.toString().includes(keyword)) ||
        (resume.graduate_year && resume.graduate_year.toString().toLowerCase().includes(keyword)) ||
        (resume.preponderance && resume.preponderance.toString().toLowerCase().includes(keyword))
    );
  });
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  filteredResumes.value = [...resumes.value];
};

// 跳转到简历详情页
const goToDetail = (resumeId) => {
  router.push(`/resume/${resumeId}`);
};

// 跳转到提交简历页
const goToCreate = () => {
  router.push('/resume/create');
};

// 跳转到导出页面
const goToExport = () => {
  router.push('/resume/export');
};
</script>

<style scoped>
/* 页面容器样式 */
.list-container {
  width: 100%;
}

.page-title {
  color: #333;
  font-size: 22px;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 统计卡片样式 */
.stats-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
  align-items: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  min-width: 120px;
}

.stat-label {
  color: #999;
  font-size: 14px;
  margin-bottom: 5px;
}

.stat-value {
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

/* 搜索框样式 */
.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.1);
}

/* 简历列表样式 */
.resume-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.resume-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.resume-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.card-name {
  color: #333;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.card-badge {
  background-color: #f0f9f4;
  color: #42b983;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 10px;
}

.card-id {
  color: #999;
  font-size: 12px;
}

.card-body {
  flex: 1;
  margin-bottom: 20px;
}

.card-item {
  color: #555;
  font-size: 14px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.card-footer {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.card-tag {
  background-color: #f5f5f5;
  color: #666;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
}

.card-action {
  text-align: right;
}

/* 空数据样式 */
.empty-container {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-text {
  font-size: 18px;
  margin-bottom: 10px;
  color: #666;
}

.empty-desc {
  font-size: 14px;
  margin-bottom: 20px;
}

/* 加载中样式 */
.loading-container {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.loading-text {
  margin-top: 15px;
  font-size: 14px;
}

/* 错误提示样式 */
.error-container {
  text-align: center;
  padding: 50px 0;
  color: #ff4d4f;
}

.error-text {
  margin-top: 15px;
  font-size: 14px;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #666;
}

.btn-secondary:hover {
  background-color: #e5e5e5;
}

.btn-primary {
  background-color: #42b983;
  color: #ffffff;
}

.btn-primary:hover {
  background-color: #359469;
}
</style>